import { Node, NodePool, Prefab, instantiate } from 'cc';

// 对象池
export class ObjectPool {
    static #instance: ObjectPool = null;
    private poolMap: { [key: string]: NodePool } = {};
    private constructor() {}
    public static get instance(): ObjectPool {
        if (!ObjectPool.#instance) ObjectPool.#instance = new ObjectPool();
        return ObjectPool.#instance;
    }

    public createNode(prefab: Prefab): Node {
        let pool = this.poolMap[prefab.name];
        if (!pool) {
            pool = new NodePool();
            this.poolMap[prefab.name] = pool;
        }
        if (pool.size() > 0) {
            return pool.get();
        }
        return instantiate(prefab);
    }

    public returnNode(node: Node): void {
        let pool = this.poolMap[node.name];
        if (!pool) return;
        pool.put(node);
    }
}
